package com.zly.mybatisdemo.interceptor;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import com.zly.mybatisdemo.token.NoneAuth;
import com.zly.mybatisdemo.token.TokenHelper;
import com.zly.mybatisdemo.utils.TokenUtils;
import com.zly.mybatisdemo.utils.SecurityConstant;
import com.zly.mybatisdemo.utils.Result;

/**
 * @ClassName LoginInterceptor
 * @Author zhaokang
 * @Description 登录拦截器
 * @Date 2021/1/21 14:26
 */
@Slf4j
@Component
public class LoginInterceptor implements AsyncHandlerInterceptor {
    @Autowired
    private TokenHelper tokenHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");//"Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,Authorization,SessionToken,JSESSIONID,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("XDomainRequestAllowed","1");

        String requestURL = request.getRequestURL().toString();
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //如果被@NoneAuth注解代表不需要登录验证，直接通过
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String beanName = handlerMethod.getBean().getClass().getName();
        if (beanName.equals("springfox.documentation.swagger.web.ApiResourceController")
                || beanName.equals("org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController")) {
            return true;
        }

        Method method = handlerMethod.getMethod();
        if (method.getAnnotation(NoneAuth.class) != null) {
            return true;
        }
        //token验证
        String token = request.getHeader(SecurityConstant.REQUEST_AUTH_HEADER);
        if (tokenHelper.check(token)) {
            String userId = TokenUtils.getClaim(token, SecurityConstant.USER_ID);
            String userName = TokenUtils.getClaim(token, SecurityConstant.USER_NAME);
            request.setAttribute(SecurityConstant.CURRENT_USER_ID, userId);
            request.setAttribute(SecurityConstant.CURRENT_USER_NAME, userName);
            //FeignContextHolder.bindUserId(userId);
            //FeignContextHolder.bindUserName(userName);
            return true;
        }
        //验证未通过
        failResult(response);
        return false;
    }

    private void failResult(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            String result = JSON.toJSONString(Result.fail("mac验证失败"));//至关重要
            writer = response.getWriter();
            writer.print(result);
        } catch (Exception e) {
            log.error(String.format("打印拦截结果异常%s", e.getMessage()), e);
        } finally {
            if (null != writer) {
                writer.close();
            }
        }

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable Exception ex) throws Exception{
        //FeignContextHolder.clear();
    }
}
